const { app, BrowserWindow, Menu, ipcMain, dialog } = require('electron')
const path = require('path')
const fs = require('fs').promises
const { spawn } = require('child_process')
const http = require('http')

// Python后端进程
let pythonProcess = null
let pythonServerPort = 8888

// 启动Python后端服务
function startPythonBackend() {
  try {
    const pythonPath = process.platform === 'win32' ? 'python' : 'python3'
    const serverPath = path.join(__dirname, 'python_backend', 'server.py')
    
    console.log('启动Python后端服务...')
    console.log(`Python路径: ${pythonPath}`)
    console.log(`服务器路径: ${serverPath}`)
    
    pythonProcess = spawn(pythonPath, [serverPath], {
      stdio: ['pipe', 'pipe', 'pipe'],
      cwd: __dirname,
      env: { ...process.env, PYTHONPATH: path.join(__dirname, 'python_backend') }
    })
    
    pythonProcess.stdout.on('data', (data) => {
      const output = data.toString().trim()
      if (output) {
        console.log(output)
      }
    })
    
    pythonProcess.stderr.on('data', (data) => {
      const error = data.toString().trim()
      if (error) {
        console.error(error)
      }
    })
    
    pythonProcess.on('close', (code) => {
      console.log(`Python后端进程退出，代码: ${code}`)
      pythonProcess = null
    })
    
    pythonProcess.on('error', (error) => {
      console.error('启动Python后端失败:', error)
      pythonProcess = null
    })
    
    // 等待Python服务启动，增加重试机制
    setTimeout(() => {
      checkPythonServerWithRetry(3)
    }, 3000)
    
  } catch (error) {
    console.error('启动Python后端失败:', error)
  }
}

// 带重试的Python服务器检查
function checkPythonServerWithRetry(retryCount) {
  if (retryCount <= 0) {
    console.error('Python服务器启动失败，已达到最大重试次数')
    return
  }
  
  checkPythonServer().then(() => {
    console.log('Python后端服务已启动')
  }).catch((error) => {
    console.log(`Python服务器检查失败，剩余重试次数: ${retryCount - 1}`)
    setTimeout(() => {
      checkPythonServerWithRetry(retryCount - 1)
    }, 2000)
  })
}

// 检查Python服务器是否运行
function checkPythonServer() {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: pythonServerPort,
      path: '/health',
      method: 'GET'
    }
    
    const req = http.request(options, (res) => {
      if (res.statusCode === 200) {
        resolve(true)
      } else {
        console.log('Python后端服务响应异常')
        reject(new Error(`HTTP ${res.statusCode}`))
      }
    })
    
    req.on('error', (error) => {
      console.error('无法连接到Python后端服务:', error)
      reject(error)
    })
    
    req.setTimeout(5000, () => {
      req.destroy()
      reject(new Error('连接超时'))
    })
    
    req.end()
  })
}

// 停止Python后端服务
function stopPythonBackend() {
  if (pythonProcess) {
    console.log('停止Python后端服务...')
    pythonProcess.kill()
    pythonProcess = null
  }
}

function createWindow() {
  const win = new BrowserWindow({
    width: 1400,
    height: 1100,
        webPreferences: {
          nodeIntegration: false,
          contextIsolation: true,
          webSecurity: true,
          allowRunningInsecureContent: false,
          preload: path.join(__dirname, 'preload.js')
        },
  })

  // 配置内容安全策略头部
  win.webContents.session.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [
          "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self' ws: wss:; object-src 'none'; base-uri 'self'; form-action 'self';"
        ]
      }
    })
  })

  win.loadURL('http://localhost:5173')
  
  // 初始化应用程序菜单
  createMenu()
}

// 创建应用程序菜单
function createMenu() {
  const template = [
    {
      label: '文件',
      submenu: [
        {
          label: '保存',
          accelerator: 'CmdOrCtrl+S',
          click: () => {
            const win = BrowserWindow.getFocusedWindow()
            if (win) {
              win.webContents.send('menu-save-file')
            }
          }
        },
        { type: 'separator' },
        {
          label: '新建窗口',
          accelerator: 'CmdOrCtrl+Shift+N',
          click: () => {
            createWindow()
          }
        },
        { type: 'separator' },
        {
          label: '退出',
          accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
          click: () => {
            app.quit()
          }
        }
      ]
    },
    {
      label: '编辑',
      submenu: [
        {
          label: '撤销',
          accelerator: 'CmdOrCtrl+Z',
          click: () => {
            const win = BrowserWindow.getFocusedWindow()
            if (win) {
              win.webContents.send('menu-undo')
            }
          }
        },
        { type: 'separator' },
        {
          label: '修改参数',
          accelerator: 'CmdOrCtrl+E',
          click: () => {
            const win = BrowserWindow.getFocusedWindow()
            if (win) {
              win.webContents.send('menu-edit-params')
            }
          }
        },
        {
          label: '重置默认参数',
          accelerator: 'CmdOrCtrl+R',
          click: () => {
            const win = BrowserWindow.getFocusedWindow()
            if (win) {
              win.webContents.send('menu-reset-params')
            }
          }
        }
      ]
    },
    {
      label: '视图',
      submenu: [
        { type: 'separator' },
        {
          label: '重新加载',
          accelerator: 'CmdOrCtrl+Shift+R',
          click: (item, focusedWindow) => {
            if (focusedWindow) focusedWindow.reload()
          }
        },
        {
          label: '切换开发者工具',
          accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Ctrl+Shift+I',
          click: (item, focusedWindow) => {
            if (focusedWindow) focusedWindow.webContents.toggleDevTools()
          }
        }
      ]
    },
    {
      label: '窗口',
      submenu: [
        {
          label: '最小化',
          accelerator: 'CmdOrCtrl+M',
          role: 'minimize'
        },
        {
          label: '关闭',
          accelerator: 'CmdOrCtrl+W',
          role: 'close'
        }
      ]
    },
    {
      label: '设置',
      accelerator: 'CmdOrCtrl+,',
      click: () => {
        const win = BrowserWindow.getFocusedWindow()
        if (win) {
          win.webContents.send('menu-open-settings')
        }
      }
    }
  ]

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

// 进程间通信处理程序
ipcMain.handle('dialog:selectFile', async (event, options) => {
  try {
    const result = await dialog.showOpenDialog({
      properties: ['openFile'],
      filters: options.filters || [
        { name: '所有文件', extensions: ['*'] }
      ]
    })
    return result
  } catch (error) {
    return { canceled: true, filePaths: [] }
  }
})

ipcMain.handle('dialog:selectDirectory', async (event, options) => {
  const result = await dialog.showOpenDialog({
    properties: ['openDirectory']
  })
  return result
})

ipcMain.handle('system:getInfo', () => {
  return {
    platform: process.platform,
    arch: process.arch,
    version: process.version,
    electronVersion: process.versions.electron
  }
})

ipcMain.handle('config:save', async (event, config) => {
  // 实现配置保存功能
  console.log('保存配置:', config)
  return { success: true }
})

ipcMain.handle('config:load', async () => {
  // 实现配置加载功能
  return { success: true, config: {} }
})

ipcMain.handle('log:write', async (event, logData) => {
  console.log(`[${logData.level}] ${logData.message}`)
  return { success: true }
})

// 项目管理相关进程间通信处理程序
ipcMain.handle('project:createStructure', async (event, projectData) => {
  try {
    const { name, path: projectPath } = projectData
    
    // 初始化项目根目录
    const projectDir = path.join(projectPath, name)
    
    // 检查目录是否已存在
    try {
      await fs.access(projectDir)
      throw new Error(`目录已存在: ${projectDir}`)
    } catch (error) {
      if (error.code === 'ENOENT') {
        // 目录不存在，允许创建
      } else if (error.message.includes('目录已存在')) {
        throw error
      } else {
        // 其他错误，继续执行创建流程
      }
    }
    
    await fs.mkdir(projectDir, { recursive: true })
    
    // 初始化项目子目录结构
    const subDirs = ['input', 'output', 'temp', 'scripts', 'results']
    for (const subDir of subDirs) {
      await fs.mkdir(path.join(projectDir, subDir), { recursive: true })
    }
    
    
    // 不生成默认 README 文件
    
    return { success: true, projectPath: projectDir }
  } catch (error) {
    console.error('创建项目结构失败:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('project:validate', async (event, projectPath) => {
  try {
    const files = await fs.readdir(projectPath)
    const foundFiles = []
    
    // 扫描所有文件
    for (const file of files) {
      const ext = path.extname(file).toLowerCase()
      const filePath = path.join(projectPath, file)
      const stats = await fs.stat(filePath)
      
      foundFiles.push({
        name: file,
        path: filePath,
        type: ext.substring(1) || 'unknown',
        size: stats.size,
        isDirectory: stats.isDirectory()
      })
    }
    
    return {
      valid: true,
      files: foundFiles,
      errors: []
    }
  } catch (error) {
    return {
      valid: false,
      files: [],
      errors: [`扫描项目失败: ${error.message}`]
    }
  }
})

ipcMain.handle('project:scan', async (event, projectPath) => {
  try {
    const stats = await fs.stat(projectPath)
    if (!stats.isDirectory()) {
      throw new Error('路径不是目录')
    }
    
    const projectName = path.basename(projectPath)
    const files = await fs.readdir(projectPath)
    
    return {
      name: projectName,
      path: projectPath,
      files: files,
      isValid: true
    }
  } catch (error) {
    return {
      name: '未知项目',
      path: projectPath,
      files: [],
      isValid: false,
      error: error.message
    }
  }
})

// 文件操作相关进程间通信处理程序
ipcMain.handle('file:read', async (event, filePath) => {
  try {
    const content = await fs.readFile(filePath, 'utf8')
    return { success: true, content }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 监听文件选择事件
ipcMain.on('file-selected', async (event, filePath) => {
  try {
    const content = await fs.readFile(filePath, 'utf8')
    event.reply('file-selected', filePath, content)
  } catch (error) {
    console.error('读取文件失败:', error)
    event.reply('file-error', error.message)
  }
})

// 监听文件保存事件
ipcMain.on('save-file', async (event, filePath, content) => {
  try {
    await fs.writeFile(filePath, content, 'utf8')
    event.reply('file-saved', filePath)
  } catch (error) {
    console.error('保存文件失败:', error)
    event.reply('file-error', error.message)
  }
})

ipcMain.handle('file:write', async (event, filePath, content) => {
  try {
    await fs.writeFile(filePath, content, 'utf8')
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('file:exists', async (event, filePath) => {
  try {
    await fs.access(filePath)
    return { success: true, exists: true }
  } catch (error) {
    return { success: true, exists: false }
  }
})

ipcMain.handle('file:list', async (event, dirPath) => {
  try {
    const files = await fs.readdir(dirPath, { withFileTypes: true })
    const result = files.map(file => ({
      name: file.name,
      path: path.join(dirPath, file.name),
      type: file.isDirectory() ? 'folder' : 'file',
      isDirectory: file.isDirectory()
    }))
    return { success: true, files: result }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 删除文件/文件夹（递归）
ipcMain.handle('file:delete', async (event, targetPath) => {
  try {
    const stat = await fs.stat(targetPath)
    if (stat.isDirectory()) {
      await fs.rm(targetPath, { recursive: true, force: true })
    } else {
      await fs.unlink(targetPath)
    }
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 重命名/移动
ipcMain.handle('file:rename', async (event, oldPath, newPath) => {
  try {
    await fs.rename(oldPath, newPath)
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 在系统资源管理器中显示
ipcMain.handle('reveal-in-explorer', async (event, targetPath) => {
  try {
    const { shell } = require('electron')
    shell.showItemInFolder(targetPath)
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// SIMION自动化相关IPC处理程序
ipcMain.handle('simion:run', async (event, config) => {
  try {
    // 检查Python服务器是否运行
    if (!pythonProcess) {
      return { 
        success: false, 
        error: 'Python后端服务器未启动，请重启应用程序' 
      }
    }
    
    const postData = JSON.stringify(config)
    const options = {
      hostname: 'localhost',
      port: pythonServerPort,
      path: '/run',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      }
    }
    
    return new Promise((resolve, reject) => {
      const req = http.request(options, (res) => {
        let data = ''
        res.on('data', (chunk) => {
          data += chunk
        })
        res.on('end', () => {
          try {
            const result = JSON.parse(data)
            resolve(result)
          } catch (error) {
            console.error('解析Python响应失败:', error)
            console.error('原始响应:', data)
            reject(new Error('解析Python服务器响应失败'))
          }
        })
      })
      
      req.on('error', (error) => {
        console.error('连接Python服务器失败:', error)
        if (error.code === 'ECONNREFUSED') {
          reject(new Error('无法连接到Python后端服务器，请检查服务器是否正在运行'))
        } else if (error.code === 'ECONNRESET') {
          reject(new Error('Python服务器连接被重置，请重试'))
        } else {
          reject(new Error(`连接错误: ${error.message}`))
        }
      })
      
      // 设置超时
      req.setTimeout(10000, () => {
        req.destroy()
        reject(new Error('请求超时，Python服务器可能无响应'))
      })
      
      req.write(postData)
      req.end()
    })
  } catch (error) {
    console.error('SIMION运行请求失败:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('simion:stop', async (event) => {
  try {
    const options = {
      hostname: 'localhost',
      port: pythonServerPort,
      path: '/stop',
      method: 'POST'
    }
    
    return new Promise((resolve, reject) => {
      const req = http.request(options, (res) => {
        let data = ''
        res.on('data', (chunk) => {
          data += chunk
        })
        res.on('end', () => {
          try {
            const result = JSON.parse(data)
            resolve(result)
          } catch (error) {
            reject(new Error('解析响应失败'))
          }
        })
      })
      
      req.on('error', (error) => {
        reject(error)
      })
      
      req.end()
    })
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('simion:status', async (event) => {
  try {
    const options = {
      hostname: 'localhost',
      port: pythonServerPort,
      path: '/status',
      method: 'GET'
    }
    
    return new Promise((resolve, reject) => {
      const req = http.request(options, (res) => {
        let data = ''
        res.on('data', (chunk) => {
          data += chunk
        })
        res.on('end', () => {
          try {
            const result = JSON.parse(data)
            resolve(result)
          } catch (error) {
            reject(new Error('解析响应失败'))
          }
        })
      })
      
      req.on('error', (error) => {
        // 如果是连接被拒绝，说明Python服务器已关闭，返回默认状态
        if (error.code === 'ECONNREFUSED') {
          resolve({ 
            success: true, 
            is_running: false, 
            stop_requested: false,
            message: 'Python服务器已关闭'
          })
        } else {
          reject(error)
        }
      })
      
      req.end()
    })
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 获取Python后端日志
ipcMain.handle('simion:logs', async (event) => {
  try {
    const options = {
      hostname: 'localhost',
      port: pythonServerPort,
      path: '/logs',
      method: 'GET'
    }
    
    return new Promise((resolve, reject) => {
      const req = http.request(options, (res) => {
        let data = ''
        res.on('data', (chunk) => {
          data += chunk
        })
        res.on('end', () => {
          try {
            const result = JSON.parse(data)
            resolve(result)
          } catch (error) {
            reject(new Error('解析响应失败'))
          }
        })
      })
      
      req.on('error', (error) => {
        // 如果是连接被拒绝，说明Python服务器已关闭，返回空日志
        if (error.code === 'ECONNREFUSED') {
          resolve({ 
            success: true, 
            logs: [],
            message: 'Python服务器已关闭'
          })
        } else {
          reject(error)
        }
      })
      
      req.end()
    })
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 停止Python服务器
ipcMain.handle('stopPythonServer', async (event) => {
  try {
    stopPythonBackend()
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 检查Python服务器状态
ipcMain.handle('checkPythonServerStatus', async (event) => {
  try {
    if (!pythonProcess) {
      return { 
        success: false, 
        running: false, 
        error: 'Python进程未启动' 
      }
    }
    
    const isRunning = await checkPythonServer()
    return { 
      success: true, 
      running: isRunning,
      port: pythonServerPort
    }
  } catch (error) {
    return { 
      success: false, 
      running: false, 
      error: error.message 
    }
  }
})

// 重启Python服务器
ipcMain.handle('restartPythonServer', async (event) => {
  try {
    console.log('重启Python服务器...')
    stopPythonBackend()
    
    // 等待进程完全停止
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    startPythonBackend()
    
    return { success: true, message: 'Python服务器重启中...' }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

app.whenReady().then(() => {
  // 启动Python后端服务
  startPythonBackend()
  
  createWindow()
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  // 停止Python后端服务
  stopPythonBackend()
  
  if (process.platform !== 'darwin') app.quit()
})

app.on('before-quit', () => {
  // 应用退出前停止Python后端
  stopPythonBackend()
})
